<template>
  <div class="word-editor">
    <h2>编辑单词</h2>
    <form @submit.prevent="saveWord">
      <div>
        <label for="id">序号:</label>
        <input type="text" id="id" v-model="word.id" disabled />
      </div>
      <div>
        <label for="word">单词:</label>
        <input type="text" id="word" v-model="word.word" />
      </div>
      <div>
        <label for="phonetic">音标:</label>
        <input type="text" id="phonetic" v-model="word.phonetic" />
      </div>
      <div>
        <label for="definition">解释:</label>
        <textarea id="definition" v-model="word.definition"></textarea>
      </div>
      <div>
        <label for="chineseDefinition">中文释义:</label>
        <textarea id="chineseDefinition" v-model="word.chineseDefinition"></textarea>
      </div>
      <button type="submit">保存</button>
    </form>
  </div>
</template>

<script>
import { mapActions, mapState } from 'vuex';
// import { useRoute } from 'vue-router';

export default {
  props: ['wordId'],
  data() {
    return {
      word: {}
    };
  },
  computed: {
    ...mapState(['words'])
  },
  methods: {
    ...mapActions(['updateWord']),
    async saveWord() {
      await this.updateWord({ id: this.wordId, word: this.word });
      this.$router.push({ name: 'WordList' });
    },
    fetchWord() {
      const word = this.words.find(w => w.id === this.wordId);
      if (word) {
        this.word = { ...word };
      } else {
        console.error(`Word with id ${this.wordId} not found.`);
      }
    }
  },
  created() {
    this.fetchWord();
  }
};
</script>


<style scoped>
.word-editor {
  border: 1px solid #ccc;
  padding: 10px;
  margin-bottom: 10px;
  border-radius: 5px;
}
h2 {
  margin: 0;
}
form div {
  margin-bottom: 10px;
}
label {
  display: block;
  margin-bottom: 5px;
}
input, textarea {
  width: 100%;
  padding: 5px;
  box-sizing: border-box;
}
button {
  background-color: #4CAF50;
  color: white;
  border: none;
  padding: 5px 10px;
  cursor: pointer;
  border-radius: 5px;
}
button:hover {
  background-color: #45a049;
}
</style>